<?php 
namespace App\Http\Controllers\TongGaoApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Models\Mysql\tonggao\term;

use Excel;
use App\Http\Controllers\TongGaoApi\ExcelActionController;
use App\Http\Controllers\TongGaoApi\WordActionController;

class BibController extends Controller
{	
	const ROUTE_PREFIX = '/api/*';
	protected $request;
	protected $curTime;
	protected $debug;
	private $option=1; //1: book4 style; 
	private	$curTextArray = array(),$curFSA = array(),$BibOutput = "";
	private $notedCBIB_ID	= array(), $notedEBIB_ID	= array();
	private $dFSA=array('name' => 'Cambria', 'size' => 11, 'italic'=>false), $iFSA=array('name' => 'Cambria', 'size' => 11, 'italic'=>true);

	private $tableInfos = array(
		'PE'=>array(
			'desc'=>'PE',
			'data'=>array(), 'fileName'=>'', 'sheetName'=>'', 'header'=>array(), 'colIndex'=>array(), 		
			'eleNames' => array('PE-NO','SelfTran','COPY','Revise','PE_CBIB_ID','PE_EBIB_ID','VolumeNo','PageNo'),		
			'h2cols' => array(
					array('col'=>'PE-NO'	 , 'header'=>"PE-NO"),
					array('col'=>'SelfTran'	, 'header'=>"自译标志"),
					array('col'=>'COPY'	 	, 'header'=>"引用标志"),
					array('col'=>'Revise'	, 'header'=>array("引文是否有改动","Y/N")),
					array('col'=>'PE_CBIB_ID'	, 'header'=>"CBIB_ID"),
					array('col'=>'PE_EBIB_ID'	, 'header'=>"BIB_ID"),
					array('col'=>'VolumeNo' , 'header'=>"译文所在卷（如英译广论有3本，需要明确是第几本）"),
					array('col'=>'PageNo'	, 'header'=>"所在页"),
					array('col'=>'PE_ChineseBookName'	, 'header'=>"Chinese Title"),
					array('col'=>'PE_CBETA_CHNBOOKNAME'	, 'header'=>"中文书名"),
			),
		),
		'ChnBib'=>array(
			'desc'=>'ChnBib',
			'data'=>array(), 'fileName'=>'', 'sheetName'=>'', 'header'=>array(), 'colIndex'=>array(), 		
			'eleNames' => array('CBIB_ID','CBETA_CHNBOOKNAME','CBETA_BOOKNO','CBETA_SUTRANO','EnglishBookName','SanskritBookName','ChineseBookName','AuthorNameInEnglish','URL'),
			'h2cols' => array(
					array('col'=>'CBETA_CHNBOOKNAME' , 'header'=>"CBETA经论名中文"),
					//array('col'=>'CBETA_BOOKNO' , 'header'=>"CBETA册号"),
					//array('col'=>'CBETA_SUTRANO' , 'header'=>"CBETA经号"),
					array('col'=>'ChineseBookName' , 'header'=>"经论书目中文名称"),
					array('col'=>'AuthorNameInEnglish', 'header'=>"造者英文名"),
					array('col'=>'BibCat' 				, 'header'=>"ABC类别"),
					array('col'=>'URL'					, 'header'=>"CBETA网址"),
					array('col'=>'Translator'         	, 'header'=>"译者英文名"),//15
					array('col'=>'PublishHouse'       	, 'header'=>"temp出版者"),//17; NOT NEEDED, just for not change code
					array('col'=>'PublishCountry'    	, 'header'=>"temp出版国家或地区"),//16;NOT NEEDED, just for not change code
					array('col'=>'PublishTime'       	, 'header'=>"temp出版时间"),//18;NOT NEEDED, just for not change code
					array('col'=>'LastModifiedDate'     , 'header'=>"Last Modified Date"),
					array('col'=>'AccessDate'    		, 'header'=>"Access Date"),
					array('col'=>'TotalVols'    		, 'header'=>"总卷数"),
					array('col'=>'BibCat' 				, 'header'=>"ABC类别"),
					array('col'=>'AuthorNameInEnglishShort', 'header'=>"造者英文名short form"),
			),
		),
		'ChnBib2'=>array(
			'desc'=>'ChnBib2',
			'data'=>array(), 'fileName'=>'', 'sheetName'=>'', 'header'=>array(), 'colIndex'=>array(), 		
			'eleNames' => array('CBIB_ID','CBETA_CHNBOOKNAME','CBETA_BOOKNO','CBETA_SUTRANO','EnglishBookName','SanskritBookName','ChineseBookName','AuthorNameInEnglish','URL'),
			'h2cols' => array(
					array('col'=>'CBIB_ID' 			 , 'header'=>"CBIB_ID"), //0
					array('col'=>'CBETA_CHNBOOKNAME' , 'header'=>"CBETA經論名中文"),
					//array('col'=>'CBETA_BOOKNO' , 'header'=>"CBETA册号"),
					//array('col'=>'CBETA_SUTRANO' , 'header'=>"CBETA经号"),
					array('col'=>'EnglishBookName' , 'header'=>"JJC English"),//"文集经论英文书名"
					array('col'=>'EnglishBookName2' , 'header'=>array("贤恳修补经名","备注：蓝色背景内容未修改、仅替换梵文。白色背景内容已修改")),
					array('col'=>'SanskritBookName' , 'header'=>"JJC Sanskrit"),//"文集经论英文书名（梵文）"
					array('col'=>'SanskritBookName2' , 'header'=>array("贤力修补经名","备注：粉色PD；白色PD未有其他来源；灰色自译")),
					array('col'=>'ChineseBookNameInBib2' , 'header'=>"经论书目中文"),
					//array('col'=>'ChineseBookNameException'		, 'header'=>"ChineseBookNameException"), //temp
					//array('col'=>'BookNameForOrdering'		, 'header'=>"JJC English"), //temp
					array('col'=>'ChineseBookNameShort' , 'header'=>"中文-short form     贤恳"),					
					array('col'=>'EnglishBookNameShort' , 'header'=>"英文-short form     贤恳"),//temp
			),
		),
		'ChnBib3'=>array(
			'desc'=>'ChnBib3',
			'data'=>array(), 'fileName'=>'', 'sheetName'=>'', 'header'=>array(), 'colIndex'=>array(), 		
			'eleNames' => array(),
			'h2cols' => array(
					array('col'=>'CBIB_ID' 			 , 'header'=>"CBIB_ID"), //0
					array('col'=>'ChineseBookNameException'		, 'header'=>"ChineseBookNameException"), //temp
					array('col'=>'CBETA_CHNBOOKNAMEException'		, 'header'=>"CBETA_CHNBOOKNAMEException"), //temp
			),
		),
		'Bib'=>array(
			'desc'=>'Bib',
			'data'=>array(), 'fileName'=>'', 'sheetName'=>'', 'header'=>array(), 'colIndex'=>array(), 		
			'eleNames' => array('Translator','EnglishBookName','ChineseBookName','SanskritBookName','AuthorNameInEnglish','CBETA_CHNBOOKNAME','CBETA_BOOKNO','CBETA_SUTRANO','MiddleLanguage','MiddleLanguageTranslator','PublishHouse','PublishCountry','PublishTime','URL'),
			'h2cols' => array(
					array('col'=>'EBIB_ID'    			, 'header'=>"BIB_ID"), //0
					array('col'=>'TypeInChinese'    	, 'header'=>"种类"), //0
					array('col'=>'Translator'         	, 'header'=>'译者英文'),//array("作者","或译者团队"):15
					array('col'=>'EnglishBookName'    	, 'header'=>"书/文摘英文名"), //12
					array('col'=>'ChineseBookName'    	, 'header'=>"书/文摘中文名NEW"), //U列
					array('col'=>'SanskritBookName'   	, 'header'=>"书/文摘梵文名"), //13
					array('col'=>'AuthorNameInEnglish'	, 'header'=>"造者英文"),// 7;
					array('col'=>'AuthorNameInEnglishNote'	, 'header'=>"作者或译者团队 (First Last )"),// 7;
					array('col'=>'AuthorNameInEnglishBib'	, 'header'=>"作者或译者团队(Last, First initial)"),// 7;
					array('col'=>'CBETA_CHNBOOKNAME'   , 'header'=>"CBETA经论名中文"),// 4;
					array('col'=>'CBETA_BOOKNO'        , 'header'=>"CBETA册号"),// 2;
					array('col'=>'CBETA_SUTRANO'       , 'header'=>"CBETA经号"),// 3;
					array('col'=>'MiddleLanguage'    	, 'header'=>"Translated from 语种"),//10;
					array('col'=>'MiddleLanguageTranslator' , 'header'=>"Translated from 译者"),//11;
					array('col'=>'PublishHouse'       	, 'header'=>"出版者"),//17;
					array('col'=>'PublishCountry'    	, 'header'=>"出版国家或地区"),//16;
					array('col'=>'PublishTime'       	, 'header'=>"出版时间"),//18;
					array('col'=>'URL'               	, 'header'=>"英文网站"),//26;
					array('col'=>'AccessDate'    		, 'header'=>"英文网站访问时间"),
					array('col'=>'URL_CBETA'            , 'header'=>"CBETA网址"),//26;
					array('col'=>'AccessDate_CBETA'    	, 'header'=>"CBETA网址访问时间"),
					array('col'=>'LastModifiedDate'     , 'header'=>"网址更新时间"),
					array('col'=>'AccessDate'    		, 'header'=>"网址访问时间"),
					array('col'=>'TotalVols'    		, 'header'=>"总卷数"),
					array('col'=>'BibCat' 				, 'header'=>"文献类型（A\B\C）"),
					array('col'=>'EnglishBookNameShort' , 'header'=>"英文Short Form"),
					array('col'=>'AuthorNameInEnglishShort' , 'header'=>"译者short form"),
					array('col'=>'ChineseBookNameShort' , 'header'=>"中 short form"),//NOW NEEDED
					//array('col'=>'BookNameForOrdering'	, 'header'=>"书/文摘英文名"),//temp
			),
		),
	);

	public function setTableInfo($book){
		
		//引文表相关信息
		$this->tableInfos['PE']['sheetName'] = "ALL";
		$this->tableInfos['PE']['StartRowIndex']=1;
		switch($book)
		{
		case 5:
			$this->tableInfos['PE']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\book5_引文文献-20180831-lishu.3(自译卷号).xlsx"
			);
			break;
		case 7:
			$this->tableInfos['PE']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\book7_引文文献-20180830-【lishu2157】.xlsx");
			break;
		case 8:
			$this->tableInfos['PE']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\book8_引文文献-20180831-【lishu1229】.xlsx");
			$this->tableInfos['PE']['sheetName'] = "第8册";
			break;
		}	

		//英文文献表相关信息
		$Bib_BIB_ID_ColIndex = 0;
		$Bib_BIB_Type_ColIndex = 1;
		$this->tableInfos['Bib']['sheetName'] = "译著";
		$this->tableInfos['Bib']['StartRowIndex']=1;
		
		switch($book){
			case 5:	case 6:	case 7: case 8:
				//$this->tableInfos['Bib']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\英文经论书目汇总20180830V3-【lishu-1202】.xls");
				$this->tableInfos['Bib']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\英文经论书目汇总20180830V4-【贤恳法师-08310824】.xls");			
				break;
		}
		//中文文献表相关信息
		$ChnBib_ChnBIB_ID_ColIndex = 0;
		$this->tableInfos['ChnBib']['StartRowIndex']=1;
		switch($book){
			case 5:	case 6:	case 7: case 8:
				//$this->tableInfos['ChnBib']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\经论中文表-新版去重-0826 - raw.xls");
				$this->tableInfos['ChnBib']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\经论中文表-去重修补校对人名0829V2-【贤恳法师-08310824】.xls");
				
				$this->tableInfos['ChnBib']['sheetName'] = "Sheet1";
				break;
		}
		
		//中文文献表2相关信息
		$this->tableInfos['ChnBib2']['StartRowIndex']=2;
		//$this->tableInfos['ChnBib2']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\文集4-8册经论书目列表-v7- 0829-晚.xlsx");				
		$this->tableInfos['ChnBib2']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\三语对照表-v7-0831-【lishu-1056】.xlsx");				
		$this->tableInfos['ChnBib2']['sheetName'] = "经论书目英文名";
		
		//中文文献表3(Exception)相关信息
		$this->tableInfos['ChnBib3']['StartRowIndex']=1;
		$this->tableInfos['ChnBib3']['fileName'] = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\history\\中文文献Exception.xlsx");
		$this->tableInfos['ChnBib3']['sheetName'] = "经论书目英文名";
	}
	
	public function	initWordInfo(&$dFSA,&$iFSA,&$textArray,&$FSA,&$bibCount){
		$dFSA=array('name' => 'Cambria', 'size' => 11, 'italic'=>false);
		$iFSA=array('name' => 'Cambria', 'size' => 11, 'italic'=>true);

		$textArray = array();
		$FSA = array();
		$bibCount = 0;
	}
	
	public function readCellData(){
		foreach($this->tableInfos as $tableInfo){
			if (!empty($tableInfo['fileName'])){
				echo "begin to read {$tableInfo['desc']} table, ";
				$temp=array();
				Excel::load($tableInfo['fileName'], function($reader) use (&$tableInfo, &$temp) {
					$desc = $tableInfo['desc'];
					$sheetName = $tableInfo['sheetName'];
					$sheetIndex = ExcelActionController::getExcelSheetIndexBySheetName($reader,$sheetName);
					if ($sheetIndex===false){
						$fileNameUTF8 = iconv('GBK', 'UTF-8', $tableInfo['fileName']);
						echo "$desc Table $fileNameUTF8 does not have the required sheet $sheetName</br>";
						exit;
					}
					echo " sheetIndex=$sheetIndex</br>";
					//$reader->setReadDataOnly(true);
					$reader = $reader->getSheet($sheetIndex);
					$temp = $reader->toArray();
				});
				$this::trimCellData($temp);
				$this->tableInfos[$tableInfo['desc']]['data'] = $temp;
			
				$tableInfo['header'] = $temp[0];
				$temp=$temp2=array();
				foreach($tableInfo['h2cols'] as $h2col){
					$temp[$h2col['col']] = getColIndex($tableInfo['header'], $h2col['header']);
					$temp2[] = $h2col['col'];
				}
				$this->tableInfos[$tableInfo['desc']]['colIndex'] = $temp;
				$this->tableInfos[$tableInfo['desc']]['eleNames'] = $temp2;
			}
		}
	}	
	
	public function intChnBib(){
		$ChnBibCellData = $this->tableInfos['ChnBib']['data'];
		$ChnBibColIndex = $this->tableInfos['ChnBib']['colIndex'];
		$ChnBib2CellData = $this->tableInfos['ChnBib2']['data'];
		$ChnBib2ColIndex = $this->tableInfos['ChnBib2']['colIndex'];
		$ChnBib3CellData = $this->tableInfos['ChnBib3']['data'];
		$ChnBib3ColIndex = $this->tableInfos['ChnBib3']['colIndex'];
		//step 1: integrate EnglishBookName/EnglishBookName2 and SanskritBookName/SanskritBookName2 for ChnBib2
		foreach($ChnBib2CellData as $i=>$row){
			if ($i<$this->tableInfos['ChnBib2']['StartRowIndex'])
				continue;
			$EnglishBookName2= $row[$ChnBib2ColIndex['EnglishBookName2']];
			$SanskritBookName2= $row[$ChnBib2ColIndex['SanskritBookName2']];
			if (!empty($EnglishBookName2)){
				//$this->tableInfos['ChnBib2']['data'][$i][$ChnBib2ColIndex['EnglishBookName']] = $EnglishBookName2;
				$ChnBib2CellData[$i][$ChnBib2ColIndex['EnglishBookName']] = $EnglishBookName2;
			}
			if (!empty($SanskritBookName2)){
				//$this->tableInfos['ChnBib2']['data'][$i][$ChnBib2ColIndex['SanskritBookName']] = $SanskritBookName2;
				if ((mb_substr($SanskritBookName2,0,mb_strlen("Avataṃsakasūtra 《华严经》")) =="Avataṃsakasūtra 《华严经》"))
					$SanskritBookName2 = "Avataṃsakasūtra";
				$ChnBib2CellData[$i][$ChnBib2ColIndex['SanskritBookName']] = $SanskritBookName2;
			}
			//if ($row[$ChnBib2ColIndex['CBIB_ID']]=='大智度论'){
				//var_dump($row);echo "EnglishBookName2={$EnglishBookName2} {$ChnBib2CellData[$i][$ChnBib2ColIndex['EnglishBookName']]}</br>";//exit;//SanskritBookName2={$SanskritBookName2} {$this->tableInfos['ChnBib2']['data'][$i][$ChnBib2ColIndex['SanskritBookName']]}
			//}
		}
		//step 2: 
		$intFields = array('CBIB_ID','EnglishBookName','SanskritBookName','EnglishBookNameShort','ChineseBookNameShort');
		$ChnColCount = count($ChnBibCellData,1)/count($ChnBibCellData,2);
		foreach($intFields as $i=>$intField){
			$this->tableInfos['ChnBib']['colIndex'][$intField] = $ChnColCount+$i;
			$this->tableInfos['ChnBib']['eleNames'] []= $intField;
			foreach($ChnBibCellData as $index=>$row)
				$this->tableInfos['ChnBib']['data'][$index][$ChnColCount+$i]="";
		}
		$ChnColCountNew = count($ChnBibCellData,1)/count($ChnBibCellData,2);
		echo "ChnColCountNew=$ChnColCountNew</br>";
		//var_dump($this->tableInfos['ChnBib']['colIndex']);
		$replace = array(
			array("大般涅盘经","大般涅槃经"),
			array("百丈丛林清规正义记","百丈丛林清规证义记"),
			array("大萨遮尼干子所说经","大萨遮尼乾子所说经"),
			array("顺朱","顺硃"),
		);
		foreach($ChnBibCellData as $index=>$row){
			if ($index<$this->tableInfos['ChnBib']['StartRowIndex'])
				continue;
			$CBETA_CHNBOOKNAME = trim($this::stripBookNameMark(trim($row[$ChnBibColIndex['CBETA_CHNBOOKNAME']])));
			$ChineseBookName = trim($this::stripBookNameMark(trim($row[$ChnBibColIndex['ChineseBookName']])));
			foreach($replace as $v){
				$CBETA_CHNBOOKNAME = str_replace($v[0],$v[1],$CBETA_CHNBOOKNAME);
				$ChineseBookName = str_replace($v[0],$v[1],$ChineseBookName);
			}
			echo "int ChineseBookName=$ChineseBookName</br>";

			if ( (!empty($CBETA_CHNBOOKNAME)) &&($CBETA_CHNBOOKNAME<>"无") &&($CBETA_CHNBOOKNAME<>"")){
				$index2 = $this::searchInAColumnOfCellData($ChnBib2CellData,$ChnBib2ColIndex['CBIB_ID'] ,$CBETA_CHNBOOKNAME);
				if ($index2===false){
					//echo "$ChineseBookName+$CBETA_CHNBOOKNAME</br>";
				}
			}else{
				//if (mb_strpos($ChineseBookName,"云栖法录（选录）",0)!==false)
				if (mb_strpos($ChineseBookName,"（古今图书集成）神异典二氏部汇考",0)!==false)
					var_dump($ChnBib2CellData[$ChnBib2ColIndex['ChineseBookNameInBib2']]);
				
				$index2 = $this::searchInAColumnOfCellData($ChnBib2CellData,$ChnBib2ColIndex['ChineseBookNameInBib2'] ,"《{$ChineseBookName}》");
				if ($index2===false){
					//echo "$ChineseBookName+$CBETA_CHNBOOKNAME</br>";
				}
			}
			if ($index2===false){
				$index2 = $this::searchInAColumnOfCellData($ChnBib2CellData,$ChnBib2ColIndex['CBIB_ID'] ,$ChineseBookName);
				if ($index2===false){
					//echo "$ChineseBookName+$CBETA_CHNBOOKNAME</br>";
				}
			}
			if ($index2===false){
				$index2 = $this::searchInAColumnOfCellData($ChnBib2CellData,$ChnBib2ColIndex['ChineseBookNameInBib2'] ,"《{$CBETA_CHNBOOKNAME}》");
				if ($index2===false){
					//echo "$ChineseBookName+$CBETA_CHNBOOKNAME</br>";
				}
			}
			if ($index2===false){
				$index3 = $this::searchInAColumnOfCellData($ChnBib3CellData,$ChnBib3ColIndex['ChineseBookNameException'] ,"《{$ChineseBookName}》");
				if ($index3===false)
					$index3 = $this::searchInAColumnOfCellData($ChnBib3CellData,$ChnBib3ColIndex['CBETA_CHNBOOKNAMEException'] ,"{$CBETA_CHNBOOKNAME}");
				if ($index3!==false){
					$CBIB_ID3 = $ChnBib3CellData[$index3][$ChnBib3ColIndex['CBIB_ID']];
					$index2 = $this::searchInAColumnOfCellData($ChnBib2CellData,$ChnBib2ColIndex['CBIB_ID'] ,$CBIB_ID3);
					if ($index2===false){
						echo "$ChineseBookName $CBETA_CHNBOOKNAME CBIB_ID3={$CBIB_ID3} but not found in ChnBib2 table</br>";
					}
				}else{
					echo "ChineseBookName=$ChineseBookName CBETA_CHNBOOKNAME={$CBETA_CHNBOOKNAME} NOT FOUND in exception table</br>";
				}
				
			}
			if ($index2!==false){
				foreach($intFields as $i=>$intField){
					//echo "here is the key: {$ChnBib2CellData[$index2][$ChnBib2ColIndex[$intField]]}</br>";
					$this->tableInfos['ChnBib']['data'][$index][$ChnColCount+$i] = $ChnBib2CellData[$index2][$ChnBib2ColIndex[$intField]];
				}
			}
			if ($ChineseBookName=="大方广佛华严经（四十卷"){
				echo "四十</br>";
				echo "before {$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]}</br>";
				$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]="四十华严";
				echo "after {$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]}</br>";
			}
			elseif ($ChineseBookName=="大方广佛华严经（六十卷）"){
				$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]="六十华严";
				echo "after {$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]}</br>";
			}
			elseif ($ChineseBookName=="大方广佛华严经（八十卷）"){
				$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]="八十华严";
				echo "after {$this->tableInfos['ChnBib']['data'][$index][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]}</br>";
			}	
		}
		//foreach($ChnBibCellData as $index=>$row){
		//	$CBETA_CHNBOOKNAME = $row[$ChnBibColIndex['CBETA_CHNBOOKNAME']];
		//	$ChineseBookName = $row[$ChnBibColIndex['ChineseBookName']];
		//	echo "ChineseBookName=$ChineseBookName  CBETA_CHNBOOKNAME=$CBETA_CHNBOOKNAME</br>";
		//	foreach($intFields as $i=>$intField){
		//		echo "$intField={$row[$ChnColCount+$i]}</br>";
		//	}
		//	echo "===========</br>";
		//}	
		//var_dump($this->tableInfos['ChnBib']['data'][1]);
		//var_dump($this->tableInfos['ChnBib2']['data'][1]);exit;
	}
	
	public function genBib(){
		set_time_limit(0);
		$bookArray = array(8);
		
		$this::initWordInfo($dFSA,$iFSA,$textArray,$FSA,$bibCount);
		foreach($bookArray as $book){
			$outputWordFile = iconv('UTF-8', 'GBK', "F:\\000_booktran\\参考文献\\test\\bib_$book.docx");
			$this::setTableInfo($book);
			$this::readCellData();
			//var_dump($this->tableInfos['ChnBib']['colIndex']);
			//echo "ChnBib Count=".count($this->tableInfos['ChnBib']['data'])."</br>";
			//var_dump($this->tableInfos['ChnBib2']['colIndex']);
			echo "ChnBib Count=".count($this->tableInfos['ChnBib']['data'])."</br>";
			echo "ChnBib2:";var_dump($this->tableInfos['ChnBib2']['colIndex']);
			echo "ChnBib3:";var_dump($this->tableInfos['ChnBib3']['colIndex']);
			echo "Bib:";var_dump($this->tableInfos['Bib']['colIndex']);
			$this::intChnBib();

			//$this::setCBIB_ID();exit;
			//generate Bibliography
			if (true){
				echo "Bibliography for book {$book}</br>";
				$this::addLineToWord("Bibliography for book {$book}", array('name' => 'Tahoma', 'size' => 30, 'italic'=>false), $bibCount, $textArray,$FSA);for($ii=0;$ii<2;$ii++)	$this::addLineBreakToWord($bibCount, $textArray,$FSA);
				
				foreach(array('A','B','C','Z','') as $curBibCat){
					$this::addLineToWord("Bibliography for book {$book} - Type ".((!empty($curBibCat))?$curBibCat:"TBD"), array('name' => 'Tahoma', 'size' => 20, 'italic'=>false), $bibCount, $textArray,$FSA);
					$bibList = $this::getSortedBibList($curBibCat);
					foreach($bibList as $bibItem){
						$SrcTable = $bibItem['SrcTable'];
						$data = array();
						$data['PerItem']=false;
						$this::table2ItemRaw($this->tableInfos[$SrcTable]['data'][$bibItem['index']],$SrcTable,$data);
						$this::itemRaw2View('Bib',$data);
						//var_dump($data);
						$this::genItemWord($data,$textArray,$FSA,$bibCount,$dFSA,$iFSA);
					}
					for($ii=0;$ii<2;$ii++)	$this::addLineBreakToWord($bibCount, $textArray,$FSA);
				}
			}
			
			if (true){
				echo "generate footnote for book {$book}</br>";
				$this::addLineToWord("FootNotes for book {$book}", array('name' => 'Tahoma', 'size' => 30, 'italic'=>false), $bibCount, $textArray,$FSA);for($ii=0;$ii<2;$ii++)	$this::addLineBreakToWord($bibCount, $textArray,$FSA);
				$this->notedCBIB_IDs = $this->notedEBIB_IDs = array();
				
				foreach($this->tableInfos['PE']['data'] as $PERowIndex=>$PERow){
					if ($PERowIndex<$this->tableInfos['PE']['StartRowIndex'])
						continue;
					if (empty($PERow)) continue;
					$data = array();
					$this::table2ItemRaw($this->tableInfos['PE']['data'][$PERowIndex],'PE',$data);
					$curPE_NO = $data['PE-NO']; $curCBIB_ID = $data['PE_CBIB_ID']; $curEBIB_ID = $data['PE_EBIB_ID'];
					if (empty($curPE_NO))
						continue;
					echo "</br>curPE_NO=$curPE_NO</br>";
					if ($data['SelfTran']==1){
						echo "It is SelfTran curCBIB_ID=$curCBIB_ID</br>";
						if (empty($curCBIB_ID)){
							echo "Generate footnote error: $curPE_NO CBIB_ID empty at row $PERowIndex</br>";
							continue;
						}
						$ChnBibRowIndex = $this::searchInAColumnOfCellData($this->tableInfos['ChnBib']['data'],$this->tableInfos['ChnBib']['colIndex']['CBIB_ID'] ,$curCBIB_ID);
						if ($curCBIB_ID=="(古今图书集成)神异典二氏部汇考"){
							echo "colIndex={$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']}</br>";
							echo "{$this->tableInfos['ChnBib']['data'][1][0]} {$this->tableInfos['ChnBib']['data'][1][1]} {$this->tableInfos['ChnBib']['data'][1][16]}</br>";
							echo "{$this->tableInfos['ChnBib']['data'][2][0]} {$this->tableInfos['ChnBib']['data'][2][1]} {$this->tableInfos['ChnBib']['data'][2][16]}</br>";
							echo "compare ".($curCBIB_ID==$this->tableInfos['ChnBib']['data'][1][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]);
						}
							
						if ($ChnBibRowIndex===false){
							echo "Generate footnote error: $curPE_NO CBIB_ID $curCBIB_ID not found at row $PERowIndex</br>";
							continue;
						}
						echo "ChnBibRowIndex=$ChnBibRowIndex</br>";
						$this::table2ItemRaw($this->tableInfos['ChnBib']['data'][$ChnBibRowIndex],'ChnBib',$data);
						$this::itemRaw2View('Note',$data);
						if (in_array($curPE_NO,array("A1.1","A1.2","A1.3")))
							var_dump($data);
						$this::genItemWord($data,$textArray,$FSA,$bibCount,$dFSA,$iFSA);
							
					}else{
						echo "It is COPY curEBIB_ID=$curEBIB_ID</br>";
						if (empty($curEBIB_ID)){
							echo "Generate footnote error: $curPE_NO EBIB_ID empty at row $PERowIndex</br>";
							continue;
						}
						
						$EngBibRowIndex = $this::searchInAColumnOfCellData($this->tableInfos['Bib']['data'],$this->tableInfos['Bib']['colIndex']['EBIB_ID'] ,$curEBIB_ID);
						if (($EngBibRowIndex===false)){
							echo "Generate footnote error: $curPE_NO EBIB_ID $curEBIB_ID not found at row ".(string)($PERowIndex+1)."</br>";//echo "Generate footnote error: EBIB_ID $curEBIB_ID not found at row $PERowIndex</br>";
							continue;
						}
						echo "EngBibRowIndex=$EngBibRowIndex</br>";
						$this::table2ItemRaw($this->tableInfos['Bib']['data'][$EngBibRowIndex],'Bib',$data);
						//var_dump($data);
						$this::itemRaw2View('Note',$data);
						if (in_array($curPE_NO,array("A1.1","A1.2","A1.3")))
							var_dump($data);
						$this::genItemWord($data,$textArray,$FSA,$bibCount,$dFSA,$iFSA);
					}
				}
			}
			
			WordActionController::exportWord_01($outputWordFile,$textArray,$FSA);
		}
	}
	
	public function trimCellData(&$cellData){
		foreach($cellData as $i=>$rowData){
			foreach($rowData as $j=>$oneCellData){
				$oneCellData = trim($oneCellData);
				if (in_array(strtoupper($oneCellData),array("NA","#N/A","0","NOT FOUND"))){
					//echo "oneCellData=$oneCellData</br>";
					//echo "{$cellData[$i][$j]}</br>";
					$oneCellData = "";
				}
				$cellData[$i][$j]=$oneCellData;
				//echo "{$cellData[$i][$j]}</br>";
			}
		}
	}

	public function searchInAColumnOfCellData(&$cellData,$colIndex,$needle,$loose=false){
		foreach($cellData as $rowIndex=>$rowData){
			$curCell = trim($rowData[$colIndex]);
			if ($loose){
				$curCell=trim($this::stripBookName($curCell));
			}
			if ($curCell==$needle)
				return $rowIndex;
		}
		return false;
	}
	
	public function getBibTypeCode($bibType){
		$bibTypeCode = false;
		switch($bibType){
			case "译著":	$bibTypeCode = "TRANCOPY";	break;
			case "论文":	$bibTypeCode = "THESIS";	break;
			case "期刊":	$bibTypeCode = "JOURNAL";	break;
			case "网址":	
			case "网站":	$bibTypeCode = "WEB";		break;
		}
		return $bibTypeCode;
	}

	public function itemRaw2View($desc, &$data){
		//var_dump($data);
		$data['BibType'] = ($data['SrcTable']=='Bib') ? $this::getBibTypeCode($data['TypeInChinese']) : "";
		$data['PerItem'] = ($desc=="Note") ? true : false;
		$data['googleBookFlag'] = (strpos($data['URL'],'books.google',0)!==false);

		$this::checkShort($data);
		$data['CBETA_CHNBOOKNAME'] = $this::stripBookNameMark($data['CBETA_CHNBOOKNAME']);
		$data['ChineseBookName'] = $this::stripBookNameMark($data['ChineseBookName']);
		$data['ChineseBookNameShort'] = $this::stripBookNameMark($data['ChineseBookNameShort']);
		$data['PublishCity'] = $data['PublishCountry']; $data['PublishYear'] = $data['PublishTime']; //temp
		//$data['AuthorBib'] = $data['AuthorNote']=$data['AuthorNameInEnglish']; 
		//$data['TranslatorBib'] = $data['TranslatorNote']=$data['Translator']; 
		$this::genAuthorInfo($data);
		$this::genTitleInfo($data);
		if ( !empty($data['TotalVols']) && $data['TotalVols']>1)
			$data['TotalVolsInfo']="{$data['TotalVols']} vols";
		$this::genPublishInfo($data);
		$this::genURLInfo($data);
		$this::genVPInfo($data);
		//var_dump($data);
	}
	
	public function genItemWord($data,&$textArray,&$FSA,&$bibCount,$dFSA,$iFSA){
		$bibCat=$data['BibCat'];
		$bibType=$data['BibType'];
		$perItem=$data['PerItem'];
		$googleBookFlag = $data['googleBookFlag'];
		
		$curPE_NO = $perItem ? $data['PE-NO'] : "";
		$this::addLineToWord($curPE_NO."  ", $dFSA, $bibCount, $textArray,$FSA);
		
		if( ($bibCat=="A") || ($bibCat=="B") || ( (in_array($bibCat,array("C","Z",""))) && (in_array($bibType,array("TRANCOPY","WEB","")) ) ) ){
			
			//$usualDeli = (($bibCat=="A") || ($bibCat=="B") || (($bibCat=="C") && (!$perItem))) ? "." : ",";
			$usualDeli = (!$perItem) ? "." : ",";
			

			
			if ( (($bibCat=="A") || ($bibCat=="B") ) && (!$googleBookFlag) )
				$fullFields = array('TitleInfo','URLInfo');
			else
				if ( ($bibType="TRANCOPY") || ($googleBookFlag) )
					if ($perItem)
						$fullFields = array('AuthorInfo1','TitleInfo','AuthorInfo2','EditionInfo','SeriesInfo','PublishInfo','URLInfo');
					else
						$fullFields  = array('AuthorInfo1','TitleInfo','AuthorInfo2','EditionInfo','TotalVolsInfo','SeriesInfo','PublishInfo','URLInfo');
				else
					$fullFields  = array('AuthorInfo1','TitleInfo','AuthorInfo2','URLInfo');
			
			if ($perItem){
				$fullFields  []= 'VPInfo';
				if ( (($bibCat=="A") || ($bibCat=="B") ) && (!$googleBookFlag) )
					$shortFields = array('ShortTitleInfo','VPInfo');
				else
					$shortFields = array('ShortAuthorInfo','ShortTitleInfo','VPInfo');
				if (!$data['short'])
					$data['FieldArray'] = array('full'=>$fullFields , 'short'=>$shortFields);
				else
					$data['FieldArray'] = array('short'=>$shortFields, 'full'=>$fullFields);
			}else{
				$shortFields = array();
				$data['FieldArray'] = array('full'=>$fullFields , 'short'=>array());
			}
						
			$this::fieldRelation($data);//var_dump($data['NEFields']);
			
			foreach($data['FieldArray'] as $key=>$fields){
				if (empty($fields))	continue;
				if ($perItem){
					if ($key=="short")
						if ($data['short'])
							$prompt = "【short】  ";
						else
							$prompt = "【short: only for backup】  ";
					else
						if ($data['short'])
							$prompt = "【full: only for backup】  ";
						else
							$prompt = "【full】  ";
					$this::addLineToWord($prompt, $dFSA, $bibCount, $textArray,$FSA);
				}
				
				$this::initWordLine();
				
				if ($perItem){
					if (strtoupper(mb_substr($data['Revise'],0,1))=="Y")
						$this::addPhraseToWord("Revised from ", $dFSA);
				}
				
				$fields = $data['NEFields'][$key];
				foreach($fields as $field){
						$fName = $field['name'];
						if (($fName<>"TitleInfo") && ($fName<>"ShortTitleInfo"))
							$this::addPhraseToWord($data[$fName], $dFSA);
						else
							foreach($data[$fName] as $sub)
								$this::addPhraseToWord($sub['str'], $sub['italic']?$iFSA:$dFSA);
						//elseif ($fName=="TitleInfo") 
						//	foreach($data['TitleInfo'] as $sub)
						//		$this::addPhraseToWord($sub['str'], $sub['italic']?$iFSA:$dFSA);
						//	else{ //it must be ShortTitleInfo
						//		//echo "debug short {$data['ShortTitleInfo']}</br>";
						//		//$this::addPhraseToWord($data[$fName], $iFSA);
						//	}
								
						$curDeli = $this::determineDeli($data, $field, $usualDeli, $key );
						
						$this::addPhraseToWord($curDeli, $dFSA);
				}
				$this::addLineToWord2($bibCount,$textArray,$FSA);		
			}
			//$this::addLineToWord("</br></br>", $dFSA, $bibCount, $textArray,$FSA);
		}
		else{
			$errorMessage = "需要手工处理，原因：大类={$bibCat}，小类={$bibType} 不支持。具体信息请查找英文文献表A列（BIB_ID）为\"{$data['EBIB_ID']}\"的行。";
			if (($perItem) && (strtoupper(mb_substr($data['Revise'],0,1))=="Y"))
				$errorMessage .= "【Note】这条译文是Revised from，请在footnote里标注";
			$this::addLineToWord($errorMessage, $dFSA, $bibCount, $textArray,$FSA);			
			//$this::addPhraseToWord($errorMessage, $dFSA);
			//$this::addLineToWord2($bibCount,$textArray,$FSA);		
		}
		if ($perItem)
			$this::addLineBreakToWord($bibCount, $textArray,$FSA);
	}
	
	public function determineDeli($data,$curField,$usualDeli,$key){
		$perItem = $data['PerItem'];
		$curDeli = "";
		if ($curField['name']==$data['LastField'][$key]){
			//$curDeli = ( ($curField['name']<>"TitleInfo") ? "." : "");
			$curDeli = ".";
			return $curDeli;
		}

		//1st char of non-last field
		//if ($curField['name']=="TitleInfo")
		if(false)
			$curDeli = "";
		elseif( ($perItem) && ($curField['next']=='PublishInfo') )
			$curDeli = "";
		else
			$curDeli = $usualDeli;
		//2nd char of non-last field
		$curDeli .= " ";
		return $curDeli;
	}
	
	public function fieldRelation(&$data){
		//var_dump($data['FieldArray']);
		//var_dump($data);
		foreach($data['FieldArray'] as $key=>$fields){
			//$fields = $data['FieldArray']['full'];$key='full';
			$nonEmptyFields = array();
			foreach($fields as $field){
				if (!empty($data[$field]))
					$nonEmptyFields []= array('name'=>$field,'prev'=>'','next'=>'');
			}
			$nonEmptyCount = count($nonEmptyFields);
			for($i=0;$i<$nonEmptyCount;$i++){
				if ($i<$nonEmptyCount-1)
					$nonEmptyFields [$i]['next'] = $nonEmptyFields [$i+1]['name'];
				else
					$data['LastField'][$key] = $nonEmptyFields [$i]['name'];
				if ($i>0)
					$nonEmptyFields [$i]['prev'] = $nonEmptyFields [$i-1]['name'];
			}
			$data['NEFields'][$key] = $nonEmptyFields;
			//var_dump($data['NEFields']);
		}
	}
	
	public function checkShort(&$data){
		$data['short']=false;
		if ($data['PerItem']){
			//echo "PE-NO={$data['PE-NO']}</br>";
			if ($data['SelfTran']){
				if (in_array($data['PE_CBIB_ID'],$this->notedCBIB_IDs) )
					$data['short']=true;
				else
					$this->notedCBIB_IDs []=$data['PE_CBIB_ID'];
			}
			else{
				//echo "EBIB_ID={$data['PE_EBIB_ID']}</br>";
				//var_dump($this->notedEBIB_IDs);
				if (in_array($data['PE_EBIB_ID'],$this->notedEBIB_IDs) )
					$data['short']=true;
				else
					$this->notedEBIB_IDs []=$data['PE_EBIB_ID'];
			}
		}
	}
	
	public function genAuthorInfo(&$data){
		$data['AuthorInfo1']=$data['AuthorInfo2']="";
		if ( (($data['BibCat']=='A') || ($data['BibCat']=='B')) && (!$data['googleBookFlag']) )
			return;
		
		if ($data['SrcTable']=='ChnBib')
			$data['AuthorInfo1'] = $data['AuthorNameInEnglish'];
		else{
			$data['AuthorInfo1'] = $data['PerItem'] ? ($data['AuthorNameInEnglishNote']) : ($data['AuthorNameInEnglishBib']);
			$data['AuthorInfo1'] = $this::capInitial($data['AuthorInfo1']);
		}
		/*
		if (!empty($data['AuthorNameInEnglish'])){
			$data['AuthorInfo1'] = $data['PerItem'] ? ($data['AuthorNote']) : ($data['AuthorBib']);
			if (!empty($data['Translator'])){
				$data['AuthorInfo2'] = $data['PerItem'] ? ("trans. ".$data['TranslatorNote']) : ($data['TranslatorBib']."trans. ");
			}
		}else{
			if (!empty($data['Translator'])){
				$data['AuthorInfo2'] = $data['PerItem'] ? ("trans. ".$data['TranslatorNote']) : ("Translated by ".$data['TranslatorBib']);
			}
		}*/
		$data['ShortAuthorInfo'] = $data['AuthorNameInEnglishShort'];
	}
	
	public function genTitleInfo(&$data){
		$data['TitleInfo']=array();
		$ChnBibColIndex = $this->tableInfos['ChnBib']['colIndex'];
		if ($data['SrcTable']=='ChnBib'){
			$ChineseBookName = (!$data['ChnBibOtherFlag']) ? $data['CBETA_CHNBOOKNAME'] :$data['ChineseBookName'];
		}else{
			$ChineseBookName = (!empty($data['CBETA_CHNBOOKNAME'])) ? $data['CBETA_CHNBOOKNAME'] : $data['ChineseBookName'];
		}
		//var_dump($data);
		//echo "ChineseBookName=$ChineseBookName</br>";
		if (!empty($data['EnglishBookName'])){
			$data['TitleInfo'][]=array('str'=>$data['EnglishBookName'],'italic'=>true);
			if ( (!empty($ChineseBookName)) || (!empty($data['SanskritBookName'])) )
				$data['TitleInfo'][]=array('str'=>', ','italic'=>false);
		}
		if (!empty($ChineseBookName)){
			$data['TitleInfo'][]=array('str'=>$ChineseBookName,'italic'=>false);
			if (!empty($data['SanskritBookName'])) 
				$data['TitleInfo'][]=array('str'=>', ','italic'=>false);
		}
		if (!empty($data['SanskritBookName'])){
			$data['TitleInfo'][]=array('str'=>$data['SanskritBookName'],'italic'=>true);
			//$data['TitleInfo'][]=array('str'=>'.','italic'=>false);
		}
		
		$data['ShortTitleInfo'] = array();
		if (!empty($data['EnglishBookNameShort'])){
			$data['ShortTitleInfo'][]=array('str'=>$data['EnglishBookNameShort'],'italic'=>true);
			if ( (!empty($data['ChineseBookNameShort'])) || (!empty($data['SanskritBookName'])) )
				$data['ShortTitleInfo'][]=array('str'=>', ','italic'=>false);
		}
		if (!empty($data['ChineseBookNameShort'])){
			$data['ShortTitleInfo'][]=array('str'=>$data['ChineseBookNameShort'],'italic'=>false);
			if (!empty($data['SanskritBookName'])) 
				$data['ShortTitleInfo'][]=array('str'=>', ','italic'=>false);
		}
		if (!empty($data['SanskritBookName'])){
			$data['ShortTitleInfo'][]=array('str'=>$data['SanskritBookName'],'italic'=>true);
			//$data['TitleInfo'][]=array('str'=>'.','italic'=>false);
		}
	}
		
	public function genPublishInfo(&$data){
		$data['PublishInfo'] = "";
		if (!empty($data['PublishCity'])){
			$data['PublishInfo'] .= "{$data['PublishCity']}";
			if (!empty($data['PublishHouse']) || !empty($data['PublishYear']))
				$data['PublishInfo'] .= ": ";
		}
		if (!empty($data['PublishHouse'])){
			$data['PublishInfo'] .= "{$data['PublishHouse']}";
			if (!empty($data['PublishYear']))
				$data['PublishInfo'] .= ", ";
		}
		if (!empty($data['PublishYear']))
			$data['PublishInfo'] .= "{$data['PublishYear']}";
		if ($data['PerItem'] && (!empty($data['PublishInfo'])) )
			$data['PublishInfo'] = "({$data['PublishInfo']})";
	}
	
	public function genURLInfo(&$data){
		if (empty($data['URL']))
			$data['URLInfo'] = "";
		$temp=array();
		if (!empty($data['LastModifiedDate']))
			$temp []= "last modified {$data['LastModifiedDate']}";
		if (!empty($data['AccessDate']))
			$temp []= "accessed {$data['AccessDate']}";
		if (!empty($data['URL']))
			$temp []= "{$data['URL']}";
		$data['URLInfo'] = implode(", ",$temp);
	}
	
	public function genVPInfo(&$data){
		$data['VPInfo']="";
		if ($data['PerItem']){
			if ( (!empty($data['VolumeNo'])) && (!empty($data['PageNo'])) )
				$data['VPInfo'] = "{$data['VolumeNo']}:{$data['PageNo']}";
			if ( (!empty($data['VolumeNo'])) && (empty($data['PageNo'])) )
				$data['VPInfo'] = "vol. {$data['VolumeNo']}";
			if ( (empty($data['VolumeNo'])) && (!empty($data['PageNo'])) )
				$data['VPInfo'] = "{$data['PageNo']}";
		}
		echo "VP={$data['VPInfo']}</br>";
	}	
	public function table2ItemRaw($src, $desc, &$data){
		$eleNames = $this->tableInfos[$desc]['eleNames'];
		$index   = $this->tableInfos[$desc]['colIndex'];
		foreach($eleNames as $eleName)
			$data[$eleName] = ((array_key_exists($eleName,$index)) && ($index[$eleName]!==false) )? $src[$index[$eleName]] : false;
		if (($desc=="ChnBib") ||  ($desc=="Bib"))
			$data['SrcTable'] = $desc;
		
		if ($desc=="ChnBib"){
			//$data['ChnBibOtherFlag'] = ((mb_substr($src[$index['CBETA_CHNBOOKNAME']],0,5))=="无"); //OTHER
			$data['ChnBibOtherFlag'] = (in_array($src[$index['CBETA_CHNBOOKNAME']],array("无",""))) ; 
		}
		
		if ($desc=="Bib"){
			$data['URL'] = (!empty($data['URL'])) ? ($data['URL']) : ($data['URL_CBETA']);
			$data['AccessDate'] = (!empty($data['AccessDate'])) ? ($data['AccessDate']) : ($data['AccessDate_CBETA']);
		}

		//var_dump($index);
		//var_dump($src);
		//var_dump($data);
	}
	
	public function getSortedBibList($curBibCat){
		$tI = $this->tableInfos;
		$orderFieldList = array();
		$bibList = array();
		foreach(array('ChnBib','Bib') as $SrcTable){
		//foreach(array('ChnBib') as $SrcTable){
			$cellData = $tI[$SrcTable]['data']; 
			$colIndex = $tI[$SrcTable]['colIndex']; 
			$startRowIndex = $tI['ChnBib']['StartRowIndex']; 
			foreach($cellData as $i=>$row){
				if ($i<$startRowIndex)	continue;
				if (empty($row[$colIndex[$SrcTable=="Bib"?'EBIB_ID':'CBIB_ID']])) continue;
				//check whether it exists in PE table
				if ($this::searchInAColumnOfCellData($this->tableInfos['PE']['data'],$this->tableInfos['PE']['colIndex'][$SrcTable=="Bib"?'PE_EBIB_ID':'PE_CBIB_ID'] ,$row[$colIndex[$SrcTable=="Bib"?'EBIB_ID':'CBIB_ID']])===false){
					echo "not exists in PE table,skipped</br>";
					continue; //if you do not want to filter for testing purpose, just comment out this line
				}else{
					echo "good, exists in PE table</br>";
				}
				if ($row[$colIndex['BibCat']]==$curBibCat){
				//if (true){ //if you do not want to filter for testing purpose, just use this line to replace the above one
					//$orderFieldList []= $row[$colIndex['BookNameForOrdering']];
					//echo "before strip {$row[$colIndex['EnglishBookName']]} </br>";
					$tempStrip = $this::stripWord($row[$colIndex['EnglishBookName']],array('a','an','the'),1);
					//echo "tempStrip=$tempStrip</br>";
					$orderFieldList []= $tempStrip;
					$bibList []= array('SrcTable'=>$SrcTable,'index'=>$i);
				}
				//$tI['ChnBib']['data'][$i]['EnglishBookForOrdering'] = $this::stripWord($tI['ChnBib']['data'][$i]['EnglishBookName']);
			}
		}
		//echo "before sorting</br>";var_dump($orderFieldList);var_dump($bibList);
		array_multisort($orderFieldList, $bibList);
		//echo "after sorting</br>";var_dump($orderFieldList);var_dump($bibList);
		return $bibList;
	}
	
	public function stripWord($str,$wordArray,$beginning){
		$StartPos = 0;
		foreach($wordArray as $word){
			$wordWs = $word." ";
			$actualStartPos = mb_strpos(strtoupper($str),strtoupper($wordWs),$StartPos);
			$length = mb_strlen($str);
			if ($actualStartPos !== false){
				if ($actualStartPos == 0){
					echo "wordws $wordWs</br>";
					echo "before strip {$str} </br>";
					echo "after strip ".mb_substr($str,mb_strlen($wordWs))." </br>";
					return mb_substr($str,mb_strlen($wordWs));
				}
			}
		}
		return $str;
	}
	
	public function stripBookNameMark($str){
		return str_replace("》","",str_replace("《","",$str));
	}
	
	public function initWordLine(){
		$this->curTextArray = array();$this->curFSA = array();$this->BibOutput = "";			
	}
	
	public function addPhraseToWord($phrase, $FSA){
		$this->BibOutput .= $phrase;
		$this->curTextArray []= $phrase;
		$this->curFSA []= $FSA; 
	}
	
	public function addLineToWord2(&$bibCount,&$textArray,&$FSA){
		$textArray[$bibCount] = $this->curTextArray;
		$FSA[$bibCount] = $this->curFSA;
		$bibCount++;		
	}
	
	public function addLineToWord($line, $lineFSA, &$bibCount,&$textArray,&$FSA){
		$textArray[$bibCount][0] = $line;
		$FSA[$bibCount][0] = $lineFSA;
		$bibCount++;
	}
	
	public function addLineBreakToWord(&$bibCount,&$textArray,&$FSA){
		$this::addLineToWord("</br></br>", $this->dFSA, $bibCount, $textArray,$FSA);	
	}
	
	public function setCBIB_ID(){
		echo "in setCBIB_ID</br>";
	
		$cellData = $this->tableInfos['PE']['data'];
		$colIndex = $this->tableInfos['PE']['colIndex'];
		foreach($cellData as $i=>$row){
			if ($i==0)	continue;
			$selfTran = $row[$colIndex['SelfTran']];
			//echo "selfTran=$selfTran</br>";
			if ($selfTran){
				$CBIB_ID = $row[$colIndex['PE_CBIB_ID']];
				$bkName = $this::stripBookNameMark($row[$colIndex['PE_ChineseBookName']]); 
				//echo "CBIB_ID=$CBIB_ID</br>";
				if (empty($CBIB_ID)){
					$ret = $this::searchInAColumnOfCellData($this->tableInfos['ChnBib']['data'],$this->tableInfos['ChnBib']['colIndex']['CBIB_ID'] ,$bkName);
					if ($ret!==false){
						//echo "ret=$ret</br>";
						echo "{$row[$colIndex['PE-NO']]} $bkName  CBIB_ID={$this->tableInfos['ChnBib']['data'][$ret][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]}</br>";
						file_put_contents("f:\\book8-found.txt","{$row[$colIndex['PE-NO']]}\t$bkName\t{$this->tableInfos['ChnBib']['data'][$ret][$this->tableInfos['ChnBib']['colIndex']['CBIB_ID']]}\r\n",8);
						
					}else{
						echo "{$row[$colIndex['PE-NO']]} $bkName  CBIB_ID_NOT_FOUND</br>";
						file_put_contents("f:\\book8-notfound.txt","{$row[$colIndex['PE-NO']]}\t$bkName\t{$row[$colIndex['PE_CBETA_CHNBOOKNAME']]}\r\n",8);
					}
				}
			}	
		}
	}
	
	public function capInitial($str){
		if (empty($str))
			return $str;
		$initial = mb_substr($str,0,1);
		$rest = mb_substr($str,1);
		return (strtoupper($initial).$rest);
	}
}
?>